import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from news.core.exceptions import NotFoundException, ValidationException
from news.core.services.news import NewsService


@csrf_exempt
@require_http_methods(["POST"])
def create_news(request):
    try:
        data = json.loads(request.body)
        news_dto = NewsService().create_news(data)
        return JsonResponse({
            'success': True,
            'data': {
                'id': news_dto.id,
                'title': news_dto.title,
                'subtitle': news_dto.subtitle,
                'content': news_dto.content,
                'content_div': news_dto.content_div,
                'category': news_dto.category,
                'status': news_dto.status,
                'created_at': news_dto.created_at.isoformat(),
                'updated_at': news_dto.updated_at.isoformat(),
                'image_list': news_dto.image_list,
                'video_list': news_dto.video_list,
                'audio_list': news_dto.audio_list,
                'editor': news_dto.editor,
                'link': news_dto.link,
                'source': news_dto.source,
                'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                'origin_id': news_dto.origin_id
            }
        }, status=201)
    except ValidationException as e:
        return JsonResponse({
            'success': False,
            'error': e.message
        }, status=e.code)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def get_news(request, news_id):
    try:
        news_dto = NewsService().get_news(news_id)
        return JsonResponse({
            'success': True,
            'data': {
                'id': news_dto.id,
                'title': news_dto.title,
                'subtitle': news_dto.subtitle,
                'content': news_dto.content,
                'content_div': news_dto.content_div,
                'category': news_dto.category,
                'status': news_dto.status,
                'created_at': news_dto.created_at.isoformat(),
                'updated_at': news_dto.updated_at.isoformat(),
                'image_list': news_dto.image_list,
                'video_list': news_dto.video_list,
                'audio_list': news_dto.audio_list,
                'editor': news_dto.editor,
                'link': news_dto.link,
                'source': news_dto.source,
                'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                'origin_id': news_dto.origin_id
            }
        })
    except NotFoundException as e:
        return JsonResponse({
            'success': False,
            'error': e.message
        }, status=e.code)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)

@csrf_exempt
@require_http_methods(["PUT"])
def update_news(request, news_id):
    try:
        data = json.loads(request.body)
        news_dto = NewsService().update_news(news_id, data)
        return JsonResponse({
            'success': True,
            'data': {
                'id': news_dto.id,
                'title': news_dto.title,
                'subtitle': news_dto.subtitle,
                'content': news_dto.content,
                'content_div': news_dto.content_div,
                'category': news_dto.category,
                'status': news_dto.status,
                'created_at': news_dto.created_at.isoformat(),
                'updated_at': news_dto.updated_at.isoformat(),
                'image_list': news_dto.image_list,
                'video_list': news_dto.video_list,
                'audio_list': news_dto.audio_list,
                'editor': news_dto.editor,
                'link': news_dto.link,
                'source': news_dto.source,
                'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                'origin_id': news_dto.origin_id
            }
        })
    except NotFoundException as e:
        return JsonResponse({
            'success': False,
            'error': e.message
        }, status=e.code)
    except ValidationException as e:
        return JsonResponse({
            'success': False,
            'error': e.message
        }, status=e.code)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)

@csrf_exempt
@require_http_methods(["DELETE"])
def delete_news(request, news_id):
    try:
        success = NewsService().delete_news(news_id)
        if not success:
            raise NotFoundException("News item not found")
        return JsonResponse({
            'success': True,
            'message': 'News deleted successfully'
        })
    except NotFoundException as e:
        return JsonResponse({
            'success': False,
            'error': e.message
        }, status=e.code)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def list_news_by_category(request, category):
    try:
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        news_list_dto = NewsService().list_news_by_category(category, page, page_size)
        return JsonResponse({
            'success': True,
            'data': {
                'items': [{
                    'id': item.id,
                    'title': item.title,
                    'subtitle': item.subtitle,
                    'category': item.category,
                    'status': item.status,
                    'created_at': item.created_at.isoformat(),
                    'editor': item.editor,
                    'source': item.source
                } for item in news_list_dto.items],
                'total': news_list_dto.total,
                'page': news_list_dto.page,
                'page_size': news_list_dto.page_size
            }
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)